﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Turtle8
{
    public partial class PracticeCard : UserControl, IMofa
    {
        public event ZimunimModifiedHandler EventZimunimModified;

        PictureBox picBox = new System.Windows.Forms.PictureBox();
        PracticeNewPanel mainNewPanel;
        ZimunimCard preZimunimCard;
        YamamTrackCard duringYamamTrackCard;
        PracticeOpenOldCard mainOldCard;
        LekachimCard postLekachimCard;

        IList<string> armyIDList = new List<string>();
        string tableName = "PracticeZimunim";
        DateTime startDate;
        DateTime endDate;
        string mofaStr = "practice";

        public bool IsOpen { get; set; }

        public IList<string> ArmyIDList
        { get { return armyIDList;  } }
        public DateTime StartDate
        {  
           get{  return startDate; }
           set {  startDate = value;  }
        }
        public DateTime EndDate
        { 
           get {  return endDate; }
           set{  endDate = value; }
        }
        public string TableName
        { get{ return tableName; } }

        public string MofaString
        { get{ return mofaStr; }}

        public PracticeCard()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            //checks whether there is a current practice. if so initialize this class variables
            initPractice();
            picBox.AccessibleName = "מסך ראשי";
        }


        public void changeMainPanel()
        {
            changeMainPanel(picBox);
        }
        //those functions are responsible of remove and add the just selected UserControl 
        private void changeMainPanel(Control ctrl)
        {
            if (!splitContainer.Panel2.Contains(ctrl))
            {
                this.splitContainer.Panel2.Controls.Clear();
                this.splitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס אימון - " + ctrl.AccessibleName;
        }
       
        public void changeDuringTabPanel(Control ctrl)
        {
            if (!duringSplitContainer.Panel2.Contains(ctrl))
            {
                this.duringSplitContainer.Panel2.Controls.Clear();
                this.duringSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס אימון - " + ctrl.AccessibleName;
        }
        public void changePreTabPanel(Control ctrl)
        {
            if (!preSplitContainer.Panel2.Contains(ctrl))
            {
                this.preSplitContainer.Panel2.Controls.Clear();
                this.preSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס אימון - " + ctrl.AccessibleName;
        }
        public void changePostTabPanel(Control ctrl)
        {
            if (!postSplitContainer.Panel2.Contains(ctrl))
            {
                this.postSplitContainer.Panel2.Controls.Clear();
                this.postSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס אימון - " + ctrl.AccessibleName;
        }


        //pre-Practice cards Button_Click handlers
        private void buttonZimunim_Click(object sender, EventArgs e) { changePreTabPanel(preZimunimCard); }

        //during-Practice cards Button_Click handlers
        private void buttonZimunimTrack_Click(object sender, EventArgs e) { changeDuringTabPanel(duringYamamTrackCard); }

        //post-Practice cards Button_Click handlers
        private void buttonLekachim_Click(object sender, EventArgs e)
        {

        }



        //PracticeCard Main events
        private void PracticeCard_Load(object sender, EventArgs e)
        {
            picBox.SizeMode = PictureBoxSizeMode.StretchImage;
            String currentDir = CompanyManager.StartupPath;
            picBox.Image = Image.FromFile(currentDir + @"\images\practice.JPG");
            picBox.Dock = DockStyle.Fill;
            changeMainPanel();
        }

        public int getTotalDays()
        {
            DateTime start = StartDate;
            DateTime end = endDate;

            return (int)(end.Subtract(start).Days + 1);
        }

        public void addSoldiersToMofa()
        {
            SqlDataAdapter da;
            if (ArmyIDList.Count > 0)
            {
                //adding rows case the table is [Yamam]
                da = duringYamamTrackCard.SqlDataAdapter;
                da.InsertCommand.Parameters["@startDate"].Value = startDate;

                // for each soldier, inserts a row per each day in 'mofa'
                foreach (string army_id in ArmyIDList)
                {
                    da.InsertCommand.Parameters["@armyID"].Value = army_id;
                    for (int i = 0; i < getTotalDays(); i++)
                    {
                        da.InsertCommand.Parameters["@date"].Value = startDate.AddDays(i);
                        SqlManager.executeNonQuery(da.InsertCommand);
                    }
                }
                
                //adding rows case the table is [PracticeZimunim]
                da = preZimunimCard.SqlDataAdapter;
                da.InsertCommand.Parameters["@startDate"].Value = startDate;

                // for each soldier, inserts a row per each day in 'mofa'
                foreach (string army_id in ArmyIDList)
                {
                    da.InsertCommand.Parameters["@armyID"].Value = army_id;
                    SqlManager.executeNonQuery(da.InsertCommand);
                }

                EventZimunimModified(this, new EventArgs());
            }
        }
        public void deleteSoldierFromMofa(DataGridViewSelectedRowCollection rows, int armyID_index)
        {
            SqlDataAdapter da;

            //edge point check
            if (rows.Count > 0)
            {       
                da = preZimunimCard.SqlDataAdapter;
                deleteSoldierFromMofa(rows,da);
                da = duringYamamTrackCard.SqlDataAdapter;
                deleteSoldierFromMofa(rows, da);
            }
        }

        private void deleteSoldierFromMofa(BaseCollection rows, SqlDataAdapter da)
        {
            da.DeleteCommand.Parameters["@startDate"].Value = startDate;

            // for each soldier, deletes it from the appropriate table associated with this adapter
            foreach (DataGridViewRow row in rows)
            {
                da.DeleteCommand.Parameters["@armyID"].Value = (String)(row.Cells["armyID"].Value);
                SqlManager.executeNonQuery(da.DeleteCommand);
            }
        }

        //if theres an open Practice, this function creates the corresponding class instances
        private void initPractice()
        {
            IsOpen = false;
            SqlCommand sqlCmd = SqlManager.SqlCommandFactory("SELECT * FROM PracticeData WHERE isClosed = 0");
            sqlCmd.Connection.Open();
            SqlDataReader reader = sqlCmd.ExecuteReader();

            //means there is an open Practice already. we allow only 1 Practice to be open at a time.
            if (reader.Read())
            {
                DateTime dt;
                dt = (DateTime)reader["startDate"];
                startDate = dt;
                dt = (DateTime)reader["endDate"];
                endDate = dt;
                labelPracticeDetails.Text = (string)reader["location"] + "." 
                                           + startDate.ToShortDateString() + "-" + endDate.ToShortDateString(); 

                reader.Close();

                preZimunimCard = new ZimunimCard(this);
                duringYamamTrackCard = new YamamTrackCard(this);
                duringYamamTrackCard = new YamamTrackCard(this);
                mainOldCard = new PracticeOpenOldCard(this);
                postLekachimCard = new LekachimCard(this);

                setEventZimunimModifiedHandler();
                
                changeDuringTabPanel(duringYamamTrackCard);
                changePostTabPanel(postLekachimCard);

                tabControl.SelectedTab = tabControl.TabPages[0];
                changePreTabPanel(preZimunimCard);

                IsOpen = true;
                
            }
            else
            {
                StartDate = DateTime.MinValue;
                EndDate = DateTime.MinValue;
            }

            sqlCmd.Connection.Close();
            reader.Close();
        }

        public void NewPracticeEvent(object o, EventArgs e)
        {
            initPractice();
            changeMainPanel(this.tabControl);
            changePreTabPanel(preZimunimCard);
        }

        private void setEventZimunimModifiedHandler()
        {
            //this event will fire when there will be modifications in the ZimunimCard (while adding\removing soldiers)
            EventZimunimModified += new ZimunimModifiedHandler(duringYamamTrackCard.refresh);
        }

        public override string ToString()
        {
            return "אימון";
        }


        private void tabControl_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tabControl.SelectedTab.Name.Equals("tabPagePre"))
                changePreTabPanel(preZimunimCard);
            else if (tabControl.SelectedTab.Name.Equals("tabPageDuring"))
                changeDuringTabPanel(duringYamamTrackCard);
            else if (tabControl.SelectedTab.Name.Equals("tabPagePost"))
                changePostTabPanel(postLekachimCard);
        }

        private void buttonOpenCurrent_Click(object sender, EventArgs e)
        {
            if (!IsOpen)
                MessageBox.Show(".אין כרגע כרטיס אימון פתוח");
            else
            {
                changeMainPanel(this.tabControl);
                changePreTabPanel(preZimunimCard);
            }
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            //case there isn't  an open Practice already
            if (!IsOpen)
            {
                mainNewPanel = new PracticeNewPanel(this);
                changeMainPanel(mainNewPanel);

            }
            else MessageBox.Show(".ישנו כרטיס אימון פתוח כרגע. לא ניתן לנהל יותר מאימון אחד בו זמנית");
        }

        private void buttonFinish_Click(object sender, EventArgs e)
        {
            string updateStr = @"UPDATE [PracticeData] SET isClosed=@isClosed WHERE startDate=@startDate";
            SqlCommand updateCmd = SqlManager.SqlCommandFactory(updateStr);
            updateCmd.Parameters.Add("@isClosed", SqlDbType.Bit).Value = true;
            updateCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
            updateCmd.ExecuteNonQuery();
            IsOpen = false;

            mainNewPanel = null;
            preZimunimCard = null;
            duringYamamTrackCard = null;
            mainOldCard = null;
            postLekachimCard = null;

            labelPracticeDetails.Text = string.Empty;
            changeMainPanel();
        }

        private void buttonOpenOld_Click(object sender, EventArgs e)
        {

        }


    }
}
    